package com.txc.pay.alipayLife.controller;


import com.txc.common.global.result.Result;
import com.txc.common.global.result.ResultCode;
import com.txc.openfeign.common.pay.utils.NotificationFileParsUtil;
import com.txc.openfeign.common.pay.vo.NotifyFileVo;
import com.txc.pay.alipayLife.service.AliPayLifeService;
import com.txc.pay.alipayLife.utils.SftpUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 支付宝生活缴费
 * @ProjectName smartWater-admin
 * @ClassReplaceFirstName AliPayLifeController
 * @Author tao
 * @Date 2023-07-13
 * @Version 1.0
 */
@RestController
@RequestMapping("/alipay")
public class AliPayLifeController
{
    @Resource
    private AliPayLifeService aliPayLifeService;
    @Resource
    private SftpUtil sftpUtil;


    /**
     * 获取原创抄表数据
     *
     * @param filePath 远程文件路径
     * @param fileName 文件名
     */
    @GetMapping("/reconciliation")
    public void reconciliation(String filePath, String fileName, HttpServletResponse response) throws IOException {
        OutputStream out = response.getOutputStream();
        // 连接
        sftpUtil.connect();
        try {
            sftpUtil.downloadFile(filePath, fileName, out);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            out.flush();
        }catch (Exception e) {
            throw new RuntimeException("文件下载失败");
        }finally {
            out.close();
            sftpUtil.disconnect();
        }
    }

    /**
     * 获取原创抄表解析后数据
     *
     * @param filePath 远程文件路径
     * @param fileName 文件名
     */
    @PostMapping("/analysisNotifyFile")
    public Result<NotifyFileVo> analysisNotifyFile(String filePath, String fileName) {
        // 连接
        try {
            sftpUtil.connect();
            return Result.ok(NotificationFileParsUtil.analysisNotifyFile(sftpUtil.downloadFile(filePath, fileName)));
        }catch (Exception e) {
            return Result.fail(ResultCode.ERROR.getCode(), e.getMessage());
        }finally {
            sftpUtil.disconnect();
        }
    }
}
